package com.webflux.tm.webflux.module.test.init;

import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Surging
 * @version 1.0
 * @ClassName UserServiceImpl
 * @date 2023-05-08 17:41
 * @desc
 */

@Repository
public class UserServiceImpl implements UserService {

    private static Map<Integer, User> users = new HashMap<>();

    public UserServiceImpl() {
        users.put(1, new User(1, "刘备"));
        users.put(2, new User(2, "曹操"));
        users.put(3, new User(3, "孙权"));
    }

    @Override
    public Mono<User> selectById(int id) {
        return Mono.just(users.get(id));
    }

    @Override
    public Flux<User> selectAllUsers() {
        return Flux.fromIterable(users.values());
    }

    @Override
    public Mono<Void> insertUser(Mono<User> userMono) {
        return userMono.doOnNext(user -> {
            int id = users.size() + 1;
            users.put(id, user);
        }).thenEmpty(Mono.empty());
    }

}
